import React, { useEffect, useState } from 'react';
import { Button, Col, Form, Input, Modal, Radio, Row, Space, Table, TreeSelect, message } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { ExclamationCircleFilled } from '@ant-design/icons';

import * as menus from '../../../api/base/menus';
import useBseGeneraHook from '../../../components/BaseGeneraForm/hook';

interface DataType {
  name: string;
  dataIndex: string
  children?: DataType[];
}

const Menus: React.FC = () => {
  const columns: ColumnsType<DataType> = [
    { title: '菜单名称', dataIndex: 'name' },
    { title: '路由', dataIndex: 'url' },
    { title: '排序', dataIndex: 'sort' },
    { title: '组件', dataIndex: 'assembly_url' },
    {
      title: '操作',
      dataIndex: 'x',
      key: 'x',
      render: (_: any, record: any) => (
        <>
          <Button type="primary" onClick={() => editClick(record, record.id)}>编辑</Button>
          <>&nbsp;</>
          <Button type="primary" onClick={() => del(record, record.id)}>删除</Button>
        </>
      ),
    },
  ]
  const { open, edit, rowId, openModal, closeModal, addModal, editModal, rowIdSelect } = useBseGeneraHook()
  const [form] = Form.useForm();
  const [list, setList] = useState<any[]>([])
  const [title, setTitle] = useState<string>('添加')


  const getList = async () => {
    const res = await menus.list().catch(err => console.log(err))
    if (res.success) {
      setList(res.data)
    }
  }

  const add = () => {
    openModal()
    addModal()
  }

  const del = (_, id: number) => {
    Modal.confirm({
      title: '确定删除',
      icon: <ExclamationCircleFilled />,
      okText: '是',
      cancelText: '否',
      onOk() {
        menus.menuDel(id).then(res => {
          if (res.success) {
            getList()
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  const editClick = (record: any, id: any) => {
    openModal()
    editModal()
    rowIdSelect(id)
    form.setFieldsValue({ ...record, id: id })
  }

  const onFinish = async (fieldsValue: any) => {
    let res = null
    if (edit) {
      res = await menus.menuCreated(fieldsValue).catch(err => console.log(err))
    } else {
      res = await menus.menuUpdate(rowId as number, fieldsValue).catch(err => console.log(err))
    }
    if (res?.success) {
      getList()
      closeModal()
    } else {
      message.error('创建失败')
    }
  }

  useEffect(() => {
    getList()
  }, [])

  return (
    <>
      <Button type="primary" onClick={() => add()}>添加</Button>

      <Table columns={columns} dataSource={list} pagination={{ hideOnSinglePage: true }} rowKey="id" />
      {/* */}
      <Modal title={title} open={open} footer={null} onCancel={() => closeModal()}>
        <Form form={form} onFinish={onFinish}  >
          <Form.Item name="node_type" rules={[{ required: true, message: '请选择类别' }]}>
            <Radio.Group  >
              <Radio.Button value={0}>菜单</Radio.Button>
              <Radio.Button value={1}>目录</Radio.Button>
              <Radio.Button value={2}>按钮</Radio.Button>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="菜单名称" name="name" rules={[{ required: true, message: '请输入菜单名称' }]}>
            <Input placeholder="请输入菜单名称" />
          </Form.Item>

          <Form.Item label="菜单编码" name="menu_code" rules={[{ required: true, message: '请输入菜单编码' }]}>
            <Input placeholder="请输入菜单编码" />
          </Form.Item>

          <Form.Item label="组件名称" name="assembly_name">
            <Input placeholder="请输入组件名称" />
          </Form.Item>

          <Form.Item label="组件路径" name="assembly_url">
            <Input placeholder="请输入组件路径" />
          </Form.Item>

          <Form.Item label="路由" name="url" rules={[{ required: true, message: '请输入路由' }]}>
            <Input placeholder="请输入路由 /home" />
          </Form.Item>

          <Form.Item label="排序" name="sort">
            <Input placeholder="请输入排序" />
          </Form.Item>


          <Form.Item label="目录" name="parent_id" rules={[{ required: true, message: '请选择层级目录' }]}>
            <TreeSelect
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={list}
              placeholder="请选择目录"
              fieldNames={{ label: 'name', value: 'id' }}
              treeDefaultExpandAll
              showSearch={true}
              allowClear
              value="parent_id"
            />
          </Form.Item>


          <Form.Item >
            <Row>
              <Col span={12}>
                <Button type="primary" htmlType="submit">
                  确认
                </Button>
              </Col>
              <Col span={12}>
                <Button onClick={() => closeModal()}>
                  取消
                </Button>
              </Col>
            </Row>
          </Form.Item>

        </Form>


      </Modal>
    </>
  );
}


export default Menus